package com.capinfo.accumulation.web.controller.collection;

import com.capinfo.accumulation.model.collection.Company;
import com.capinfo.accumulation.model.collection.CompanyHistory;
import com.capinfo.accumulation.parameter.collection.CompanyHistoryParameter;
import com.capinfo.accumulation.parameter.collection.CompanyParameter;
import com.capinfo.accumulation.service.collection.CompanyHistoryService;
import com.capinfo.accumulation.service.collection.CompanyService;
import com.capinfo.accumulation.service.collection.CompanyUtilService;
import com.capinfo.accumulation.web.Constants;
import com.capinfo.commons.project.model.security.SystemUser;
import com.capinfo.commons.project.parameter.security.SystemResourceParameter;
import com.capinfo.commons.project.service.security.SystemUserService;
import com.capinfo.commons.project.utils.JsonUtils;
import com.capinfo.commons.project.web.controller.manage.region.RegionManageController;
import com.capinfo.framework.model.dictionary.Dictionary;
import com.capinfo.framework.service.CommonsDataOperationService;
import com.capinfo.framework.util.IOUtils;
import com.capinfo.framework.util.LogUtils;
import com.capinfo.framework.web.controller.CommonsDataManageController;
import com.capinfo.framework.web.util.ControllerUtils;
import com.capinfo.framework.web.util.WebRequestUtils;
import com.capinfo.framework.web.view.model.DataListViewModel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.*;

/**
 * Created by wangyulin on 2017/9/27.
 */


@Controller
@RequestMapping("/business/collection/company")
public class CompanyController extends CommonsDataManageController<CompanyParameter, Company> {

    private static final Log logger = LogFactory.getLog(RegionManageController.class);
    @Autowired
    private CompanyService companyService;

    @Autowired
    private CompanyHistoryService companyHistoryService;

    @Autowired
    private CompanyUtilService companyUtilService;
    @Autowired
    private SystemUserService systemUserService;



    @RequestMapping("/is_exist.shtml")
    public void isExist(NativeWebRequest request, CompanyParameter parameter, OutputStream stream) {
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);

        if (null == parameter.getEntity().getId()) {

            Company company = companyService.isExist(parameter);

            Map map = new HashMap<String, Object>();
            if (company == null) {

                map.put("result", false);
                map.put("errCode", 1L);
                map.put("errMsg", "查无此公司");

            } else {
                map.put("result", true);
                map.put("errCode", 0L);
                map.put("errMsg", "");
//               map.put("company",company);
            }

            try {
                IOUtils.outputByStream(stream, JsonUtils.toJson(map).toString().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                LogUtils.debugException(logger, e);
            }
        }
    }

    @RequestMapping("/company_audit.shtml")
    public void audit(NativeWebRequest request, CompanyParameter parameter, OutputStream stream) throws UnsupportedEncodingException {
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);

        Boolean token = companyService.audit(parameter);
        if (token) {
            JSONObject json = new JSONObject();
            json.put("id", parameter.getEntity().getId());
            json.put("result", "success");
            IOUtils.outputByStream(stream, json.toString().getBytes("UTF-8"));
        } else {

            IOUtils.outputByStream(stream, Boolean.FALSE.toString().getBytes());
        }
    }

    @Override
    protected void saveOrUpdateAfterInvoke(NativeWebRequest request, CompanyParameter parameter, Company entity) {
        WebRequestUtils.setContentType(request, "application/json;charset=UTF-8");

        Object nativeResponse = request.getNativeResponse();
        if (nativeResponse instanceof ServletResponse) {

            HttpServletResponse response = (HttpServletResponse) nativeResponse;
            OutputStream stream = null;
            try {
                stream = response.getOutputStream();
                boolean token = entity == null ? false : true;
                if (token) {
                    JSONObject json = new JSONObject();
                    json.put("id", entity.getId());
                    json.put("result", "success");

                    IOUtils.outputByStream(stream, json.toString().getBytes("UTF-8"));
                } else {

                    IOUtils.outputByStream(stream, Boolean.FALSE.toString().getBytes());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public CommonsDataOperationService<Company, CompanyParameter> getCommonsDataOperationService() {

        return companyService;
    }

    @Override
    protected CompanyParameter saveOrUpdateBeforeInvoke(NativeWebRequest request, CompanyParameter parameter) {

        return super.saveOrUpdateBeforeInvoke(request, parameter);
    }

    @Override
    protected Map<String, Object> formAfterInvoke(NativeWebRequest request, CompanyParameter parameter, Map<String, Object> viewModel) {
        Set<Dictionary> natureAccountIdList = companyService.getDictionariesBySortName("账户性质");
        viewModel.put("natureAccountIdList", natureAccountIdList);
        Set<Dictionary> regionIdList = companyService.getDictionariesBySortName("区县");
        viewModel.put("regionIdList", regionIdList);
        Set<Dictionary> companyEconomicTypeIdList = companyService.getDictionariesBySortName("经济类型");
        viewModel.put("companyEconomicTypeIdList", companyEconomicTypeIdList);
        Set<Dictionary> companyRelatoinshipsIdList = companyService.getDictionariesBySortName("隶属关系");
        viewModel.put("companyRelatoinshipsIdList", companyRelatoinshipsIdList);
        Set<Dictionary> organizationTypeIdList = companyService.getDictionariesBySortName("机构类型");
        viewModel.put("organizationTypeIdList", organizationTypeIdList);
        Set<Dictionary> legalPersonIdCardTypeIdList = companyService.getDictionariesBySortName("证件类型");
        viewModel.put("legalPersonIdCardTypeIdList", legalPersonIdCardTypeIdList);
        Set<Dictionary> contactIdCardTypeIdList = companyService.getDictionariesBySortName("证件类型");
        viewModel.put("contactIdCardTypeIdList", contactIdCardTypeIdList);
        Set<Dictionary> depositRateMarkIdList = companyService.getDictionariesBySortName("缴存率标志");
        viewModel.put("depositRateMarkIdList", depositRateMarkIdList);


        return super.formAfterInvoke(request, parameter, viewModel);
    }


//
//
//    protected Map<String, Object> formfterInvoke(CompanyParameter parameter, Map<String, Object> viewModel) {
//
//        return viewModel;
//    }

    /**
     * 通过借口查询工商信息
     */
    @RequestMapping("/get_legal_person.shtml")
    @ResponseBody
    public String getCompanyInfo(CompanyParameter parameter) {
        Company company = companyUtilService.getLegalPersonInfo(parameter.getCompanyCode());
//        JSONObject object = JSONObject.fromObject(company);
        JSONObject object = new JSONObject();
        object.put("gbLegalPersonIdCardNumber", company.getGbLegalPersonIdCardNumber());
        object.put("gbLegalPersonName", company.getGbLegalPersonName());
        object.put("legalPersonIdCardTypeId", company.getLegalPersonIdCardTypeId());
        object.put("legalPersonMobilePhone", company.getLegalPersonMobilePhone());
        return object.toString();
    }

    /**
     * 弹出双岗审核的dialog
     *
     * @param request
     * @param parameter
     * @return
     */
    @RequestMapping("/review.shtml")
    public Map<String, Object> initial(NativeWebRequest request, SystemResourceParameter parameter) {

        Map<String, Object> viewModel = new HashMap<String, Object>();

        return viewModel;
    }


    /**
     * 验证用户名密码
     *
     * @param reviewUsername
     * @param reviewPassword
     * @return
     */
    @RequestMapping("/company_review_user.shtml")
    @ResponseBody
    public String companyReviewUser(String reviewUsername, String reviewPassword) throws UnsupportedEncodingException {
        SystemUser systemUser = systemUserService.getSystemUserByLogonNameAndPassword(reviewUsername, reviewPassword);
        JSONObject json = new JSONObject();
        json.toString().getBytes("UTF-8");
        if (systemUser != null) {
            json.put("result", true);
            json.put("userId", systemUser.getId());
        } else {
            json.put("result", false);
            json.put("errMsg", "用户名密码错误!");
        }
        return json.toString();
    }

//    @RequestMapping("/form_option.shtml")
//    public ModelAndView index(NativeWebRequest request, CompanyParameter parameter) {
//        Company company = (Company) WebRequestUtils.retrieveSessionAttribute(request, Constants.COMPANY_BINDING_ATTRIBUTE_KEY);
//        System.out.println(company.getGbCompanyName());
//
//        Map viewModel = new HashMap<String, Object>();// 字典
//        ModelAndView mav = new ModelAndView();
//        if (parameter.getAccountType() == 0L) {
//            mav.setViewName("/business/collection/company/form"); //基本账户
//        } else {
//         //   mav.setViewName("/business/collection/company/supplement_form"); //补充账户
//        }
//        parameter.setEntity(company);
//        mav.addObject("command", parameter);
//        mav.addAllObjects(formOptionAfterInvoke(parameter, viewModel));
//        return mav;
//    }

    @RequestMapping("/binding.shtml")
    public void binding(NativeWebRequest request, CompanyParameter parameter, Writer writer) {

        WebRequestUtils.cleanupSessionAttribute(request, Constants.COMPANY_BINDING_ATTRIBUTE_KEY);

        Company company = companyService.getCompanyById(parameter.getEntity().getId());

        boolean token = false;
        if (null != company) {

            WebRequestUtils.storeSessionAttribute(request, Constants.COMPANY_BINDING_ATTRIBUTE_KEY, company);

            token = true;
        }

        IOUtils.outputByWriter(writer, token);
    }

    @RequestMapping("/unbinding.shtml")
    public void unbinding(NativeWebRequest request, Writer writer) {

        //WebRequestUtils.retrieveSessionAttribute(request, Constants.COMPANY_BINDING_ATTRIBUTE_KEY);
        WebRequestUtils.cleanupSessionAttribute(request, Constants.COMPANY_BINDING_ATTRIBUTE_KEY);

        IOUtils.outputByWriter(writer, true);
    }

    /**
     * 获取单位信息
     * 张旭
     * 2017年10月24日11:20:56
     */

    @RequestMapping("/get_company.shtml")
    @ResponseBody
    public String getCompany(NativeWebRequest request, CompanyParameter parameter) {
        Company company = (Company) WebRequestUtils.retrieveSessionAttribute(request, Constants.COMPANY_BINDING_ATTRIBUTE_KEY);
        JSONObject companyJson = new JSONObject();
        if (company != null) {
            companyJson = JSONObject.fromObject(company);
            companyJson.put("result", true);
        } else {
            Company getCompany = companyService.getCompany(parameter);
            if (getCompany != null) {
                companyJson.put("result", true);
//                companyJson = JSONObject.fromObject(getCompany);
                companyJson.put("entityPerson.companyId", getCompany.getId());
                companyJson.put("companyAccount", getCompany.getGbCompanyAccount());
//                companyJson.put("company.gbCompanyName", getCompany.getGbCompanyName());
                companyJson.put("companyName", getCompany.getGbCompanyName());
                //单位缴存比例
                companyJson.put("entity.companyPaymentRatio", getCompany.getCompanyAccountFunds().get(0).getCompanyPaymentRatio());
                //个人缴存比例
                companyJson.put("entity.personPaymentRatio", getCompany.getCompanyAccountFunds().get(0).getPersonPaymentRatio());
                //缴存率标志
                companyJson.put("depositRateMarkId", getCompany.getCompanyAccountFunds().get(0).getDepositRateMarkId());
                //单位公积金id
                companyJson.put("entity.companyAccountFundId", getCompany.getCompanyAccountFunds().get(0).getId());




            }else{
                companyJson.put("result", false);
            }
        }
        return companyJson.toString();

    }

    //网点记录页面加载
    //fjs
    @RequestMapping("/site_record.shtml")
    public Map<String, Object> siteRecord(CompanyParameter parameter) {

        return ControllerUtils.buildViewModel(parameter);
    }

    //网点更改页面
    //fjs
   @RequestMapping("/site_form.shtml")
    public Map<String, Object> siteForm(CompanyParameter parameter) {

        return ControllerUtils.buildViewModel(parameter);
    }


    /*@RequestMapping("/company_site_form.shtml")
    public String companySiteForm(NativeWebRequest request, CompanyParameter parameter) {
       //Company company = (Company) WebRequestUtils.retrieveSessionAttribute(request, Constants.COMPANY_BINDING_ATTRIBUTE_KEY);
        JSONObject companyJson = new JSONObject();
       // if (company != null) {
        //    companyJson = JSONObject.fromObject(company);
        //    companyJson.put("result", true);
      //  }else {
            Company getCompany = companyService.getCompany(parameter);
            if (getCompany != null) {
                companyJson.put("result", true);

                companyJson.put("company.id", getCompany.getId());
                //单位账号
                companyJson.put("company.gbCompanyAccount", getCompany.getGbCompanyAccount());
                //补充公积金账号
                //companyJson.put("company.", getCompany.);
                //统一社会信用代码
                companyJson.put("company.creditCode", getCompany.getCreditCode());
                //单位名称
                companyJson.put("company.gbCompanyName", getCompany.getGbCompanyName());
                //单位联系地址
                companyJson.put("company.companyAddress", getCompany.getCompanyAddress());
                //联系人姓名
                companyJson.put("company.contactName", getCompany.getContactName());
                //联系人移动电话
                companyJson.put("company.contactMobilePhone", getCompany.getContactMobilePhone());
                //缴存网店
                companyJson.put("company.paymentSite", getCompany.getPaymentSite());

            } else {
                companyJson.put("result", false);
            }
        //}
        return companyJson.toString();
    }*/

    //网点变更显示的信息
    @RequestMapping("/get_company_site_form.shtml")
    @ResponseBody
    public String getCompany_site(NativeWebRequest request, CompanyParameter parameter) {
        Company company = (Company) WebRequestUtils.retrieveSessionAttribute(request, Constants.COMPANY_BINDING_ATTRIBUTE_KEY);
        JSONObject companyJson = new JSONObject();
        if (company != null) {
            companyJson = JSONObject.fromObject(company);
            companyJson.put("result", true);
        } else {
            Company getCompany = companyService.getCompany(parameter);
            if (getCompany != null) {
                companyJson.put("result", true);

                companyJson.put("entity.id", getCompany.getId());
                //单位账号
                companyJson.put("entity.gbCompanyAccount", getCompany.getGbCompanyAccount());
                //补充公积金账号
                //companyJson.put("company.", getCompany.);
                //统一社会信用代码
                companyJson.put("entity.creditCode", getCompany.getCreditCode());
                //单位名称
                companyJson.put("entity.gbCompanyName", getCompany.getGbCompanyName());
                //单位联系地址
                companyJson.put("entity.companyAddress", getCompany.getCompanyAddress());
                //联系人姓名
                companyJson.put("entity.contactName", getCompany.getContactName());
                //联系人移动电话
                companyJson.put("entity.contactMobilePhone", getCompany.getContactMobilePhone());
                //缴存网店
                companyJson.put("entity.paymentSite", getCompany.getPaymentSite());
                //历史ID
                companyJson.put("companyHistoryId", getCompany.getCompanyHistoryId());

            } else {
                companyJson.put("result", false);
            }

        }
        return companyJson.toString();

    }

    //保存变更的网点
    @RequestMapping("/save_change_site_company.shtml")
    public String saveChangeSiteCompany(NativeWebRequest request, CompanyParameter companyParameter, OutputStream stream) {

        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);
        List list = new ArrayList();

        JSONObject jsonObject = new JSONObject();

        SystemUser user = (SystemUser) WebRequestUtils.retrieveSessionAttribute(request, Constants.ADMIN_ATTRIBUTE_KEY);


        try {
            companyService.saveChangeSiteCompany(companyParameter);

            jsonObject.put("result", "true");
            jsonObject.put("entity.id", companyParameter.getEntity().getId());

        } catch (Exception e) {

            jsonObject.put("result", "false");
            LogUtils.debugException(logger, e);
        }

        try {

            IOUtils.outputByStream(stream, jsonObject.toString().getBytes("UTF-8"));

        } catch (UnsupportedEncodingException e) {

            LogUtils.debugException(logger, e);
        }
    return jsonObject.toString();
    }

    //单位信息变更记录页面加载
    //fjs
    @RequestMapping("/company_info_search.shtml")
    public ModelAndView companyInfoSearch(NativeWebRequest request, CompanyParameter parameter) {
        Map<String, Object> viewModel = ControllerUtils.buildViewModel(parameter);
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/business/collection/company_info_change/search");
        mav.addAllObjects(viewModel);
        return mav;
    }
    //单位基本信息变更记录页面加载
    //fjs
    @RequestMapping("/basic_company_info.shtml")
    public ModelAndView basicCmpanyInfo(NativeWebRequest request,CompanyParameter parameter) {
        ModelAndView modelAndView = new ModelAndView();
        Company company=companyService.basicInfo(parameter);
        modelAndView.setViewName("/business/collection/company_info_change/basic_info_form");
        CompanyParameter companyParameter = new CompanyParameter();
        companyParameter.setEntity(company);
        modelAndView.addObject("command",companyParameter);
        return modelAndView;
    }

    //保存单位基本信息的修改
    @RequestMapping("/save_company_basic_info.shtml")
    public String saveCompanyBasicInfo(NativeWebRequest request, CompanyParameter companyParameter, OutputStream stream) {

        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);

        JSONObject jsonObject = new JSONObject();

        SystemUser user = (SystemUser) WebRequestUtils.retrieveSessionAttribute(request, Constants.ADMIN_ATTRIBUTE_KEY);


        try {
            companyService.saveCompanyBasicInfo(companyParameter);

            jsonObject.put("result", "true");
            jsonObject.put("entity.id", companyParameter.getEntity().getId());

        } catch (Exception e) {

            jsonObject.put("result", "false");
            LogUtils.debugException(logger, e);
        }

        try {

            IOUtils.outputByStream(stream, jsonObject.toString().getBytes("UTF-8"));

        } catch (UnsupportedEncodingException e) {

            LogUtils.debugException(logger, e);
        }
        return jsonObject.toString();
    }

    //单位关键信息变更记录页面加载
    //fjs
    @RequestMapping("/major_company_info.shtml")
    public ModelAndView majorCmpanyInfo(NativeWebRequest request,CompanyParameter parameter) {
        ModelAndView modelAndView = new ModelAndView();
        Company company=companyService.basicInfo(parameter);
        modelAndView.setViewName("/business/collection/company_info_change/major_info_form");
        CompanyParameter companyParameter = new CompanyParameter();
        companyParameter.setEntity(company);
        modelAndView.addObject("command",companyParameter);
        return modelAndView;
    }

    //保存单位基本信息的修改
    @RequestMapping("/save_company_major_info.shtml")
    public String saveCompanyMajorInfo(NativeWebRequest request, CompanyParameter companyParameter, OutputStream stream) {

        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);

        JSONObject jsonObject = new JSONObject();

        SystemUser user = (SystemUser) WebRequestUtils.retrieveSessionAttribute(request, Constants.ADMIN_ATTRIBUTE_KEY);


        try {
            companyService.saveCompanyBasicInfo(companyParameter);

            jsonObject.put("result", "true");
            jsonObject.put("entity.id", companyParameter.getEntity().getId());

        } catch (Exception e) {

            jsonObject.put("result", "false");
            LogUtils.debugException(logger, e);
        }

        try {

            IOUtils.outputByStream(stream, jsonObject.toString().getBytes("UTF-8"));

        } catch (UnsupportedEncodingException e) {

            LogUtils.debugException(logger, e);
        }
        return jsonObject.toString();
    }
}
